<template>
  <div>
    <!-- 搜索條件卡片 -->
    <el-card class="box-card">
      <el-row :gutter="10" style="padding: 5px 5px; line-height: 28px" align="middle">
        <el-col :sm="5" :md="4" style="text-align: right">{{ $t('common.searchKey') }}</el-col>
        <el-col :sm="19" :md="12" style="text-align: left">
          <el-input
            v-model="searchKey"
            @keyup.enter="handleSearch"
            :placeholder="
              $t('common.inputText') +
              $t('user.code') +
              '/' +
              $t('user.name') +
              '/' +
              $t('common.enName') +
              '/' +
              $t('user.account')
            "
          />
        </el-col>
        <el-col :sm="24" :md="8" style="text-align: right">
          <div style="margin-right: -5px">
            <el-button @click="handleSearch" type="primary" size="small" plain
              ><Icon icon="ic:outline-search" /><span>{{ $t('common.query') }}</span></el-button
            >
            <el-button @click="searchKey = ''" type="info" size="small" plain>
              <Icon icon="icon-park-solid:clear-format" /><span>{{
                $t('common.reset')
              }}</span></el-button
            >
            <el-button type="success" size="small" plain @click="toAddStaff" v-if="hasAuth('add')">
              <Icon icon="material-symbols:add-circle-rounded" /><span>{{ $t('common.add') }}</span>
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="formcard">
      <!-- 搜索結果表頭 -->

      <!-- 搜索結果表格 -->
      <el-table
        :data="tableView"
        tooltip-effect="light"
        style="width: 100%; border-color: #a0cfff"
        :max-height="tableHeight"
        stripe
        class="companyList"
        :header-cell-style="{
          background: 'var(--el-color-primary-light-9)',
          color: '#409eff'
        }"
      >
        <el-table-column
          prop="userCode"
          :label="$t('user.code')"
          show-overflow-tooltip
          min-width="120"
        />
        <el-table-column
          prop="userName"
          :label="$t('user.account')"
          show-overflow-tooltip
          min-width="120"
        />
        <el-table-column
          prop="name"
          :label="$t('user.name')"
          show-overflow-tooltip
          min-width="120"
        />
        <el-table-column
          prop="enName"
          :label="$t('common.enName')"
          show-overflow-tooltip
          min-width="120"
        />
        <el-table-column
          prop="userType"
          :label="$t('user.type')"
          show-overflow-tooltip
          min-width="100"
        >
          <template #default="{ row }">
            <span v-if="row.userType == '1'">{{ $t('user.type1') }}</span>
            <span v-else>{{ $t('user.type0') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="mobileNo"
          :label="$t('user.mobile')"
          show-overflow-tooltip
          min-width="120"
        />
        <el-table-column
          prop="status"
          :label="$t('common.status')"
          show-overflow-tooltip
          min-width="80"
        >
          <template #default="{ row }">
            <span>{{ $t('user.' + row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.operation')" width="170">
          <template #default="{ row }">
            <el-button
              type="success"
              plain
              circle
              size="small"
              :title="$t('common.check')"
              @click="toEditStaff('look', row.userId)"
              v-if="hasAuth('detail')"
            >
              <el-icon>
                <View />
              </el-icon>
            </el-button>
            <el-button
              type="primary"
              plain
              circle
              size="small"
              :title="$t('common.modify')"
              @click="toEditStaff('update', row.userId)"
              v-if="hasAuth('edit') && hasEditAuth(row.userType)"
            >
              <el-icon>
                <Edit />
              </el-icon>
            </el-button>
            <el-button
              type="danger"
              plain
              circle
              size="small"
              :title="$t('common.delete')"
              @click="delStaff(row.userId)"
              v-if="hasAuth('delete') && hasEditAuth(row.userType)"
            >
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
            <el-button
              type="warning"
              plain
              circle
              size="small"
              :title="$t('login.resetPassword')"
              v-if="hasAuth('resetPassword') && hasEditAuth(row.userType)"
              @click="openDialog(row)"
            >
              <Icon icon="ph:password-bold" />
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分頁器 -->
      <div class="demo-pagination-block">
        <el-pagination
          v-model:currentPage="paramData.pageNo"
          v-model:page-size="paramData.pageSize"
          @current-change="changePage"
          @size-change="changePageSize"
          :page-sizes="pageSizes"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        />
      </div>
    </el-card>

    <!-- 重置密碼對話框 -->
    <el-dialog v-model="dialogVisible" :title="$t('login.resetPassword')" width="500px" draggable>
      <el-form ref="formRef" :model="dialogForm" :rules="dialogRule">
        <el-form-item :label="$t('login.password')" label-width="auto" prop="newPassword">
          <el-input
            v-model="dialogForm.newPassword"
            type="password"
            :placeholder="$t('login.passwordPlaceholder')"
            autocomplete="off"
            :show-password="true"
            maxlength="32"
            :minlength="pwLength"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t('common.cancel') }}</el-button>
          <el-button type="primary" @click="resetPsd">{{ $t('common.ok') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, onMounted, onActivated, ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { View, Edit, Delete } from '@element-plus/icons-vue'
import { formatTime, getMd5Password } from '@/utils'
import { updatePassword, getSettings, getPasswordStrength } from '@/api/company'
import { getStaff, delUser } from '@/api/staff'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useAppStore } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
import { getUserPageAuth } from '@/api/system/authority'
import { hasElementAuth } from '@/utils/authority'
import { useI18n } from '@/hooks/web/useI18n'
import { getCurUser } from '@/utils'
import { Paging } from '@/config/public'
import { useLocaleStoreWithOut } from '@/store/modules/locale'

export default {
  name: 'StaffData',
  components: {
    View,
    Edit,
    Delete
  },
  props: {},
  setup() {
    const { push, currentRoute } = useRouter()
    const appStore = useAppStore()
    const { wsCache } = useCache()
    const { t } = useI18n()
    const formRef = ref()
    const localeStore = useLocaleStoreWithOut()
    const curLang = localeStore.getCurrentLocale.lang

    const state = reactive({
      searchKey: '',
      // 表格數據
      tableHeight: 400,
      tableView: [],
      branchList: [],
      // 分頁相關屬性
      totalCount: 0,
      pageSizes: Paging.sizes,
      paramData: {
        key: '',
        pageNo: 1,
        pageSize: Paging.defaultSize,
        params: {},
        sortField: '',
        sortOrder: ''
      },
      pwLength: 6,
      pwStrength: 3,
      // 对话框绑定的数据
      dialogVisible: false,
      dialogForm: {
        newPassword: '',
        userId: ''
      },
      dialogRule: {
        newPassword: [
          { required: true, message: t('login.errPasswordEmpty'), trigger: ['blur', 'change'] },
          {
            pattern:
              /^[A-Za-z0-9`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{3,32}$/,
            message: t('common.errPassportNo'),
            trigger: ['blur', 'change']
          }
        ]
      },
      pageAuths: [{}]
    })
    onMounted(async () => {
      //获取租户配置
      const setting = await getSettings()
      state.pwLength = setting.pwLength
      state.pwStrength = setting.pwStrength
      init()
      nextTick(() => {
        state.tableHeight = window.innerHeight - 300 // - tableRef.value.$el.offsetTop - 85
        // 监听浏览器高度变化
        window.onresize = () => {
          state.tableHeight = window.innerHeight - 300 // - tableRef.value.$el.offsetTop - 85
        }
      })
      let menuId = currentRoute.value.meta.id as string
      state.pageAuths = (await getUserPageAuth(menuId)).data
    })
    useEmitt({
      //刷新列表事件
      name: 'refreshStaffList',
      callback: () => {
        init()
      }
    })
    onActivated(async () => {})
    const methods = {
      // 登錄時間
      format(time) {
        return formatTime(time, 'yyyy-MM-dd HH:mm:ss')
      },
      changePage(page) {
        state.paramData.pageNo = page
        init()
      },
      changePageSize(pageSize) {
        state.paramData.pageSize = pageSize
        state.paramData.pageNo = 1
        init()
      },
      // 新增員工跳轉
      toAddStaff() {
        wsCache.set('staffStatus', null)
        wsCache.set('staffId', null)
        push({ name: 'EditStaff' })
      },
      // 新增/修改員工跳轉
      toEditStaff(type, id) {
        wsCache.set('staffStatus', type)
        wsCache.set('staffId', id)
        push({ name: 'EditStaff' })
      },
      // 刪除
      delStaff(id) {
        ElMessageBox.confirm(t('common.delMessage'), t('common.warning'), {
          confirmButtonText: t('common.ok'),
          cancelButtonText: t('common.cancel'),
          type: 'warning'
        })
          .then(async () => {
            await delUser({ userId: id })
            init()
          })
          .catch(() => {})
      },
      // 重置密碼
      openDialog(row) {
        state.dialogForm.newPassword = row.password
        state.dialogForm.userId = row.userId
        state.dialogVisible = true
      },
      resetPsd() {
        formRef.value.validate(async (vaild) => {
          if (vaild) {
            let form = Object.assign({}, state.dialogForm)
            let strength = getPasswordStrength(form.newPassword)
            if (strength < state.pwStrength) {
              ElMessage.warning(t('settings.strengthCheck'))
              return
            }
            form.newPassword = getMd5Password(form.newPassword)
            await updatePassword(form).then((res) => {
              if (res) {
                state.dialogVisible = false
                init()
              }
            })
          }
        })
      },
      // 是否有授权
      hasAuth(key) {
        return hasElementAuth(state.pageAuths, key)
      },
      //是否有编辑权限（普通员工不能修改管理员信息）
      hasEditAuth(type) {
        //当前员工类型
        let curType = getCurUser().userType
        if (curType == 'Admin') {
          return true
        } else if (type == 0) {
          return true
        }
        return false
      },
      // 搜索
      handleSearch() {
        state.paramData.key = state.searchKey
        init()
      }
    }
    //渲染页面的接口
    const init = async () => {
      appStore.setFooter(false)
      await getStaff(state.paramData)
        .then((res) => {
          const aaa = res as any
          state.tableView = aaa.result.data
          state.totalCount = aaa.result.totalCount
        })
        .catch(() => {})
    }
    return {
      ...toRefs(state),
      formRef,
      init,
      ...methods,
      curLang
    }
  }
}
</script>
<style lang="less" scoped>
:deep(.el-card__header) {
  border-bottom: 0;
  box-sizing: border-box;
}

.searchIcon {
  background-color: #ecf5ff;
  border-color: #a0cfff;
  color: #409eff;
  cursor: pointer;
}

.el-input {
  font-size: 12px;
}

.el-option {
  font-size: 12px;
}

:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
}

.el-select-dropdown__item {
  font-size: 12px;
}

:deep(.v-footer) {
  height: 0px;
}

.input-with-select {
  width: 50%;
  margin-left: auto;
  margin-right: auto;
}

.companyList {
  font-size: 12px;
}

:deep(.el-pagination__sizes > .el-select) {
  margin-top: -3px;
}

.demo-pagination-block {
  display: flex;
  justify-content: center;
  justify-items: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
:deep(.el-pager li) {
  font-size: 12px;
  height: 28px;
  margin-top: -1px;
}

.formcard {
  margin-top: 8px;
}
</style>
